package com.swx.identityservice.exception;

import com.swx.identityservice.utils.JaxrsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.AccessDeniedException;

/**
 *统一异常处理
 * Created by SCBP
 */
@RestControllerAdvice  //也可以使用ControllerAdvice
@Slf4j
public class ScbpControllerException {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JaxrsResponse exception(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        String message = ex.getMessage();
        return JaxrsResponse.builder().message(message).code(401).build();
    }


    @ExceptionHandler({ AccessDeniedException.class })
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public JaxrsResponse badRequestException(AccessDeniedException exception) {
        log.info("====" + HttpStatus.FORBIDDEN.getReasonPhrase());
        return JaxrsResponse.builder().status(String.valueOf(HttpStatus.FORBIDDEN.value())).data(HttpStatus.FORBIDDEN.getReasonPhrase()).message(exception.getMessage()).build();
    }

    @ExceptionHandler({ MissingServletRequestParameterException.class, HttpMessageNotReadableException.class,
        UnsatisfiedServletRequestParameterException.class, MethodArgumentTypeMismatchException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JaxrsResponse badRequestException(Exception exception) {
        return  JaxrsResponse.builder().status(HttpStatus.BAD_REQUEST.value() + "").message( exception.getMessage()).build();
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JaxrsResponse exception(Throwable throwable) {
        log.error("系统异常", throwable);
        return  JaxrsResponse.builder().status(HttpStatus.BAD_REQUEST.value() + "").message(throwable.getMessage()).build();
    }

    @ExceptionHandler({ IllegalArgumentException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JaxrsResponse badRequestException(IllegalArgumentException exception) {
        return  JaxrsResponse.builder().status(HttpStatus.BAD_REQUEST.value() + "").message( exception.getMessage()).build();
    }

}
